package com.xhsj.user.sms.purchase.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhsj.user.sms.purchase.entity.TbPurchaseTask;
import com.xhsj.user.sms.purchase.entity.TbPurchaseTaskList;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseOrderGoodsMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTaskListMapper;
import com.xhsj.user.sms.purchase.query.PurchaseApplyQuery;
import com.xhsj.user.sms.purchase.query.SaveTaskUserQuery;
import com.xhsj.user.sms.purchase.service.TbPurchaseTaskListService;
import com.xhsj.user.sms.purchase.service.TbPurchaseTaskService;
import com.xhsj.user.sms.purchase.vo.FindApplyListVo;
import com.xhsj.user.sms.purchase.vo.PurchaseApplyQueryVo;
import com.xhsj.user.utils.Message;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//import org.springframework.security.access.prepost.PreAuthorize;


/**
 * <p>
 * 采购任务表 前端控制器
 * </p>
 *
 * @author suxiaolin
 * @since 2020-05-25
 */
@Slf4j
@Api(tags = "采购任务表")
@RestController
@RequestMapping("/purchase/tbPurchaseTask")
public class TbPurchaseTaskController {

    @Autowired
    public TbPurchaseTaskService service;

    @Autowired
    private TbPurchaseTaskListMapper tbPurchaseTaskListMapper;
    @Autowired
    private TbPurchaseTaskListService tbPurchaseTaskListService;

    @Autowired
    private TbPurchaseOrderGoodsMapper tbPurchaseOrderGoodsMapper;


    @ApiOperation(value = "采购任务表,保存/修改", notes = "采购任务表,保存和修改方法")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:purchase:task:edit')")
    public Message save(@RequestBody TbPurchaseTask data) {
        try {
            service.saveTask(data);
            return Message.success("成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, e.getMessage());
        }
    }

    @ApiOperation(value = "通过id查询采购任务信息", notes = "通过id查询采购任务信息")
    @RequestMapping(value = "/getPurchaseTaskById", method = RequestMethod.GET)
    public Message getPurchaseTaskById(@RequestParam("id") String id) {
        try {
            TbPurchaseTask tbPurchaseTask = service.getPurchaseTaskInfoById(id);
            return Message.success("成功", tbPurchaseTask);
        } catch (Exception e) {
            log.error("失败:{}", e);
            return Message.error(1, "失败");
        }

    }

    @ApiOperation(value = "保存任务指派用户", notes = "保存任务指派用户")
    @RequestMapping(value = "/saveTaskUser", method = RequestMethod.POST)
    public Message saveTaskUser(@RequestBody @Valid SaveTaskUserQuery saveTaskUserQuery, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
        }

        try {
            service.saveTaskUser(saveTaskUserQuery);
            return Message.success("成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }
    }

    @ApiOperation(value = "通过任务id查询子任务数量", notes = "通过任务id查询子任务数量")
    @RequestMapping(value = "/getSubTaskCountByTaskId", method = RequestMethod.GET)
    public Message getSubTaskCountByTaskId(@RequestParam("id") String id) {
        int count = service.getSubTaskCountByTaskId(id);
        return Message.success("成功", count);
    }

    @ApiOperation(value = "撤回任务", notes = "撤回任务")
    @RequestMapping(value = "/reCall", method = RequestMethod.GET)
    public Message reCall(@RequestParam("id") String id) {

        try {
            int i = service.delPurchaseTaskById(id);
            if (i == 0) {
                return Message.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("撤回失败:",e);
            return Message.error();
        }
        return Message.success();
    }

    /**
     * 通过合同id删除合同申请相关数据
     *
     * @author 苏小林
     * @date 2020/5/26 17:01
     */
    @ApiOperation(value = "通过合同id删除合同申请相关数据", notes = "通过合同id删除合同申请相关数据")
    @RequestMapping(value = "/delContractInfoById", method = RequestMethod.GET)
    public Message delContractInfoById(@RequestParam("id") String id) {

        try {
            service.delContractInfoById(id);
            return Message.success("成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }
    }


    /**
     * 获取任务清单
     *
     * @author 苏小林
     * @date 2020/5/26 17:01
     */
    @ApiOperation(value = "获取任务清单", notes = "获取任务清单")
    @RequestMapping(value = "/getPurchaseTaskList", method = RequestMethod.GET)
    public Message getPurchaseTaskList(@RequestParam("taskId") String taskId) {
        try {
            QueryWrapper<TbPurchaseTaskList> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "item_no", "item_name", "specification", "apply_number", "unit", "price", "total_money");
            queryWrapper.eq("purchase_task_id", taskId);
            List<TbPurchaseTaskList> list = tbPurchaseTaskListService.list(queryWrapper);
            List<TbPurchaseTaskList> list1 = tbPurchaseOrderGoodsMapper.getOrderGoodsListByTaskId(taskId);
            Iterator<TbPurchaseTaskList> iterator = list.iterator();
            while (iterator.hasNext()) {

                TbPurchaseTaskList next = iterator.next();
                for (TbPurchaseTaskList tbPurchaseTaskList : list1) {
                    if (tbPurchaseTaskList.getId().equals(next.getId())) {
                        iterator.remove();
                    }
                }
            }

            return Message.success("成功", list);
        } catch (Exception e) {
            log.error("出错:{}", e);
            return Message.error();
        }
    }


    @ApiOperation(value = "分页查询采购任务表list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
    @RequestMapping(value = "/findList", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:purchase:task:view')")
    public Message findList(@RequestBody Map<String, Object> data) {
        try {

            IPage<TbPurchaseTask> page = service.findPurchaseTaskList(data);
//        	IPage<TbPurchaseTask> selectPage = service.selectPage(data);
            return Message.success("成功", page.getRecords(), page.getTotal(), page.getPages());
        } catch (Exception e) {
            log.error("查询异常:{}", e);
            return Message.error(1, "失败");
        }
    }

    @ApiOperation(value = "查询采购申请列表", notes = "查询采购申请列表")
    @PostMapping(value = "/findApplyList")
    public Message findApplyList(@RequestBody @Valid PurchaseApplyQuery purchaseApplyQuery, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError allError : bindingResult.getAllErrors()) {
                log.error("参数校验:{}", allError.getDefaultMessage());
                return Message.error(1, allError.getDefaultMessage());
            }
        }
        IPage<TbPurchaseTask> page = new Page<>(purchaseApplyQuery.getPage(), purchaseApplyQuery.getSize());
        IPage<FindApplyListVo> tbPurchaseApplyIPage = service.findApplyList(page, purchaseApplyQuery);
        return Message.success("成功", tbPurchaseApplyIPage.getRecords(), tbPurchaseApplyIPage.getTotal(), tbPurchaseApplyIPage.getPages());
    }

    /**
     * 查询用户信息
     * @author 苏小林
     * @date 2020/7/31 9:49
     */
    @GetMapping(value = "/findPurchaseUser")
    public List<Object> findPurchaseUserInfo() {
        List<Object> list = service.findPurchaseUserInfo();
        return list;
    }

    /**
     * 通过id获取采购任务表实体类
     * @author 苏小林
     * @date 2020/7/31 9:49
     */
    @ApiOperation(value = "通过id获取采购任务表实体类", notes = "通过id获取采购任务表实体类。")
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:purchase:task:view')")
    public Message getById(@RequestParam(value = "id") String id) {
        PurchaseApplyQueryVo tbPurchaseTask = service.getPurchaseTaskById(id);
        return Message.success("成功", tbPurchaseTask);
    }

    @ApiOperation(value = "通过id获取实体类详细信息", notes = "通过id获取实体类详细信息。")
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:purchase:task:view')")
    public Message detail(@RequestParam(value = "id") String id) {
        return Message.success("成功", service.getById(id));
    }

    @ApiOperation(value = "查询采购任务表数据", notes = "查询采购任务表数据。")
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public Message findAll() {
        return Message.success("成功", service.selectAll());
    }

}

